﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.DataService;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Data;

namespace CommunitySystem
{
    public partial class NewMenuItemWindow : ChildWindow
    {
        private CommunitySystem.DataService.MenuItem _item = null;
        private DataService.DataServiceClient client = null;
        private CommunitySystem.Model.Silverlight.MenuItem _SItem = null;
        private int errorCount = 0;
        public NewMenuItemWindow(CommunitySystem.DataService.MenuItem item, CommunitySystem.DataService.MenuItem pitem, string tilte)
        {
            InitializeComponent();
            this.BindingValidationError += (sender, e) =>
            {
                if (e.Action == ValidationErrorEventAction.Added)
                {
                    errorCount++;
                }
                else if (e.Action == ValidationErrorEventAction.Removed)
                {
                    errorCount--;
                }
            };
            _item = item;
            client = new DataService.DataServiceClient();
            //client.GetMenuByContidtionAsync("1=1");
          //dict.DictCode="select"
            
            if (item == null && pitem != null)
            {
                _item = new DataService.MenuItem() { PID = pitem.ID };
            }
            else if(item == null && pitem == null)
            {
                _item = new DataService.MenuItem();
            }
            client.GetMenuByContidtionCompleted += (sender, e) =>
            {
                var list = e.Result.Where(c => c.ID != _item.ID);
                //LayoutRoot.DataContext = _item;
                //ParentCB.ItemsSource = list;
                if (_item != null)
                {
                    var selectitem = list.Where(d => d.ID == _item.PID);
                    //if(selectitem != null)
                    //    ParentCB.SelectedItem = selectitem.FirstOrDefault();
                }
            };
            dictMenu.Parameter = new string[] { "Id=" + _item.ID };
            _SItem = CommunitySystem.Model.Silverlight.EntityConvertor.Convert<CommunitySystem.Model.Silverlight.MenuItem>(_item);
            this.DataContext = _SItem;

            if (_SItem.IsDefault)
            {
                RBYes.IsChecked = true;
                this.RBYes_Click(RBYes, null);

            }
            else
            {
                RBNo.IsChecked = true;
                this.RBYes_Click(RBNo, null);
            }


            if (_item.icon != null && _item.icon.Length > 0)
            {
                BitmapImage b = new BitmapImage();
                Stream mm = new MemoryStream();
                mm.Write(_item.icon, 0, _item.icon.Length);
                b.SetSource(mm);
                img.Source = b;
            }
            this.Title = tilte;
        }


       

       

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            bool NeedToValid = false;
            client = new DataServiceClient();
            try
            {
                BindingExpression beUsername = tbTitle.GetBindingExpression(TextBox.TextProperty);
                beUsername.UpdateSource();
                //int count = Validation.GetErrors().Count;
                if (errorCount > 0)//判断是否有验证失败
                    return;
                //int index = int.Parse(indextb.Text);
                _item = CommunitySystem.Model.Silverlight.EntityConvertor.Convert<DataService.MenuItem>(_SItem);
                if (_item.IsDefault && _item.PID == 0)
                {
                    NeedToValid = true;
                    client.GetMenuByContidtionAsync("pid =0 and IsDefault=1 and id<>" + _item.ID);
                    client.GetMenuByContidtionCompleted -= new EventHandler<GetMenuByContidtionCompletedEventArgs>(client_GetMenuByContidtionCompleted);
                    client.GetMenuByContidtionCompleted += new EventHandler<GetMenuByContidtionCompletedEventArgs>(client_GetMenuByContidtionCompleted);
                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("必须输入数字");
                indextb.Text = 0 + "";
                return;
            }
            
            try
            {
                if (!NeedToValid)
                {
                    if (_item.ID > 0)
                    {
                        client.UpdateMenuItemAsync(_item);
                        client.UpdateMenuItemCompleted += (sender1, e1) =>
                        {
                            SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                            this.DialogResult = true;
                        };
                    }
                    else
                    {
                        client.AddMenuItemAsync(_item);
                        client.AddMenuItemCompleted += (sender1, e1) =>
                        {
                            SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                            this.DialogResult = true;
                        };
                    }
                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void client_GetMenuByContidtionCompleted(object sender, GetMenuByContidtionCompletedEventArgs e)
        {
            if (e.Result != null && e.Result.Count > 0)
            {

                if (MessageBox.Show("目前系统默认打开页面为" + e.Result[0].Title + ", 确认修改主页么?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    if (_item.ID > 0)
                    {
                        client.UpdateMenuItemAsync(_item);
                        client.UpdateMenuItemCompleted += (sender2, e2) =>
                        {
                            SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                            this.DialogResult = true;
                        };
                    }
                    else
                    {
                        client.AddMenuItemAsync(_item);
                        client.AddMenuItemCompleted += (sender2, e2) =>
                        {
                            SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                            this.DialogResult = true;
                        };
                    }
                    
                }
            }
            else
            {
                if (_item.ID > 0)
                {
                    client.UpdateMenuItemAsync(_item);
                    client.UpdateMenuItemCompleted += (sender2, e2) =>
                    {
                        SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                        this.DialogResult = true;
                    };
                }
                else
                {
                    client.AddMenuItemAsync(_item);
                    client.AddMenuItemCompleted += (sender2, e2) =>
                    {
                        SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                        this.DialogResult = true;
                    };
                }
               
            }
        }

        

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //CommunitySystem.DataService.MenuItem item = ParentCB.SelectedItem as CommunitySystem.DataService.MenuItem;
            //_item.PID = item.ID;

        }

        /// <summary>
        /// 上传新的图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            var open = new OpenFileDialog()
            {
                Filter = "图片 (*.png)|*.png"
            };
            if (open.ShowDialog() == true)
            {
                try
                {
                    FileStream stream = open.File.OpenRead();
                    
                    //_item.icon = new byte[stream.Length];
                    byte[] bs =  new byte[stream.Length];
                    BitmapImage bi = new BitmapImage();
                    stream.Read(bs, 0, bs.Length);
                    _SItem.icon = bs;
                    bi.SetSource(stream);
                    img.Source = bi;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("上传失败");
                }
                //_item.icon = stream.t();
                //ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                //imageSourceConverter.ConvertTo(img, 
            }
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //TextBox tb = sender as TextBox;
            //try
            //{
            //    int index = int.Parse(tb.Text);
            //}
            //catch(Exception ex)
            //{
            //    MessageBox.Show("必须输入数字");
            //    tb.Text = 0 + "";
            //}
        }

        private void indextb_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            
        }

        private void RBYes_Click(object sender, RoutedEventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb != null)
            {
                if (rb.Name.Equals("RBYes") && rb.IsChecked == true)
                {
                    _SItem.IsDefault = true;
                }
                else if(rb.Name.Equals("RBNo") && rb.IsChecked == true)
                {
                    _SItem.IsDefault = false;
                }
            }
        }

        

    }
}

